import { nonnull } from "../utils/common";

class UserViewModel {
  isLogin () {
    const user = this.getUserInfo();
    return user && user.username;
  }

  getAvatar () {

  }

  getPerms () {

  }

  getRoleId () {

  }

  setUserInfo (res) {
    res.projects = nonnull(res.projects);
    localStorage.setItem('userInfo', JSON.stringify(res));
  }

  getUserInfo () {
    return JSON.parse(localStorage.getItem('userInfo'));
  }

  setToken (token) {
    localStorage.setItem('token', token);
  }

  getToken () {
    return localStorage.getItem('token');
  }

  setExpire (expire_time) {
    localStorage.setItem('expire_time', expire_time);
  }

  getExpire () {
    return localStorage.getItem('expire_time');
  }

  setGroupInfo (groupInfo) {
    localStorage.setItem('group', groupInfo);
  }

  getGroupInfo () {
    return localStorage.getItem('group');
  }

  getGroupId () {
    return JSON.parse(localStorage.getItem('userInfo')).group_id;
  }

  // 这个方法不能返回 null/undefined
  getDefaultProject () {
    let proj = {}
    const userInfo = localStorage.getItem('userInfo')
    const currentChoice = localStorage.getItem('currentChoice')
    if (currentChoice) {
      proj = JSON.parse(currentChoice)
    } else if (userInfo) {
      proj = JSON.parse(userInfo).projects[0] || {}
    }
    return proj;
  }

  getDefaultProjectId () {
    const defaultProj = this.getDefaultProject();
    return defaultProj.id;
  }

  getProjects () {
    return JSON.parse(localStorage.getItem('userInfo')).projects || [];
  }

  clear () {
    localStorage.removeItem('userInfo');
    localStorage.removeItem('expire_time');
    localStorage.removeItem('token');
    localStorage.removeItem('currentChoice');
  }
}


export const userVM = new UserViewModel();
